﻿namespace wToggle.Platform
{
    using System.Collections.Generic;
    using System.Threading.Tasks;

    using Windows.Networking.Connectivity;

    using wToggle.Platform.Data;
    using wToggle.Platform.Interfaces;

    using XPlatUtils;

    public static class Toggly
    {
        static Toggly()
        {
            ServiceContainer.Register<ITogglAuth>(TogglAuth.Create);
        }

        public static void Initialize()
        {
            ServiceContainer.Register<IWorkspaceProvider>(new WorkspaceProvider());
            ServiceContainer.Register<IClientProvider>(new ClientProvider());
            ServiceContainer.Register<ITagProvider>(new TagProvider());
            ServiceContainer.Register<IProjectProvider>(new ProjectProvider());
            ServiceContainer.Register<ITimeEntryProvider>(new TimeEntryProvider());
        }

        public static async Task<AuthStatus> Authenticate(string username, string password)
        {
            var result = await ServiceContainer.Resolve<ITogglAuth>().Authenticate(username, password).ConfigureAwait(false);
            return result;
        }

        public static async Task<AuthStatus> Authenticate(string apiKey)
        {
            var result = await ServiceContainer.Resolve<ITogglAuth>().Authenticate(apiKey).ConfigureAwait(false);
            return result;
        }

        public static async Task<IEnumerable<Workspace>> GetWorkspaces()
        {
            var provider = ServiceContainer.Resolve<IWorkspaceProvider>();
            return await provider.GetWorkspaces();
        }

        public static async Task<IEnumerable<Client>> GetClients()
        {
            var provider = ServiceContainer.Resolve<IClientProvider>();
            return await provider.GetClients();
        }

        public static async Task<IEnumerable<Tag>> GetTags(ulong workspaceId)
        {
            var provider = ServiceContainer.Resolve<ITagProvider>();
            return await provider.GetTags(workspaceId);
        }

        public static async Task<IEnumerable<Project>> GetProjects(ulong workspaceId)
        {
            var provider = ServiceContainer.Resolve<IProjectProvider>();
            return await provider.GetProjects(workspaceId);
        }

        public static bool HasInternetAccess()
        {
            var connectionProfile = NetworkInformation.GetInternetConnectionProfile();

            if (connectionProfile == null)
            {
                return false;
            }

            var level = connectionProfile.GetNetworkConnectivityLevel();
            if (level == NetworkConnectivityLevel.InternetAccess || level == NetworkConnectivityLevel.ConstrainedInternetAccess)
            {
                return true;
            }

            return false;
        }
    }
}
